var app = getApp();
var ux = require('../../../../lib/ux.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bgImgPath:"",
    openSettingBtnHidden:false,
    obj:{},
    shareImage: '',
    shareShow: true,
    qrCodeUrl:"/api/memberCoupon/smallProgramCode.do",
    yjyqUrl: "/api/memberCoupon/getYjyqCouponData.do",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var self = this;
    //  高度自适应
    wx.getSystemInfo({
      success: function (res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth;
        self.setData({
          winheight: clientHeight,
          winwidth: clientWidth
        });
      }
    });
    wx.setNavigationBarTitle({
      title: '邀请有礼',
    })
    this.setData({
      userInfo: wx.getStorageSync("userInfo"),
      banrdId: wx.getStorageSync("banrdId")
    })
    self.downLoadImg(wx.getStorageSync("userInfo").header, 'header');
    var pamars = { banrdId: this.data.banrdId };
    wx.showLoading({
      title: '加载中...',
    })
      var pama = { banrdId: self.data.banrdId };
      ux.request(self.data.yjyqUrl, pama, function (protocol) {
        self.setData({
          obj: protocol.data.obj
        })
        wx.hideLoading();
        self.drawImg();
      }, true);
  },
  // 把网络图片改成临时路径
  downLoad: function (e) {
    var that = this;
    //缓存canvas背景图
    wx.downloadFile({
      url: wx.getStorageSync("userInfo").header,//网络路径
      success: function (res3) {
        //背景图
        that.setData({
          bgImgPath: res3.tempFilePath
        })
      }
    })
  },
  downLoadImg: function (netUrl, storageKeyUrl) {
    wx.getImageInfo({
      src: netUrl,    //请求的网络图片路径
      success: function (res) {
        //请求成功后将会生成一个本地路径即res.path,然后将该路径缓存到storageKeyUrl关键字中
        // wx.setStorageSync("token", data.data.token);
        wx.setStorage({
          key: storageKeyUrl,
          data: res.path,
        });

      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
     * 用户点击右上角分享
     */
  onShareAppMessage: function () {
    var self = this;
    wx.showShareMenu({
      withShareTicket: true
    })
    var shareObj = {
      title: '',
      path: '/pages/brandSelect?otherId=' + wx.getStorageSync("userInfo").uid,
      imageUrl: '',
      success: function (res) {
        console.log(JSON.stringify(res));
      },
      fail: function () {
        wx.showToast({
          title: '转发失败',
        })
      }
    }
    return shareObj;
  },
  toast: function (params) {
    if (typeof (params) == "string") {
      params = { content: params };
    }
    this.setData({
      toast: params.content
    });
    var THIS = this;
    setTimeout(function () {
      THIS.setData({
        toast: false
      });
      if (params.complete) {
        params.complete();
      }
    }, params.time || 3000);
  },
  drawImg: function () {
    if (this.data.shareImage) {
      var that = this;
      that.setData({
        shareShow: true,
      })
    } else {
      var that = this;
      that.setData({
        shareShow: true,
      })
      this.drawSharePic("刘代英", "电视卡", "/lib/dute.mp/res/fxbgs.png",this.data.obj);
    }

  },
  /**
* 绘制分享的图片
* @param goodsPicPath 商品图片的本地链接
* @param qrCodePath 二维码的本地链接
*/
  drawSharePic: function (username, carname, bgPicPath,obj) {
    var that = this;
    that.setData({
      shareShow: true,
    })
    wx.showLoading({
      title: '正在生成图片...',
      mask: true,
    });
    //y方向的偏移量，因为是从上往下绘制的，所以y一直向下偏移，不断增大。
    let yOffset = 20;
    const goodsTitle = "赛车手";
    let goodsTitleArray = [];
    var size = that.setCanvasSize();
    const imgWidth = this.data.winwidth;
    const imgHeight = this.data.winheight;
    var title1 = "特别体验券";
    var title2 ="";
    console.log(JSON.stringify(obj));
    
  
    var title3 = this.data.userInfo.nickName;
    var title4 = "免费送您一张优惠券，赶快领取吧！";
    var ctx = wx.createCanvasContext('shareCanvas')

    ctx.drawImage(bgPicPath, 0, 0, imgWidth, imgHeight*0.85)   //画海报

    if (obj.days != -1) {
      title2 = obj.days + "天";
      //绘制第2行文字
      ctx.setFontSize(imgWidth * 0.050);
      ctx.setFillStyle('#DDC086');
      ctx.setTextAlign('left');
      ctx.fillText(title2, imgWidth * 0.64, imgHeight * 0.160);
      //绘制第2行文字
    } else {
      title2 = "已过期";
      //绘制第2行文字
      ctx.setFontSize(imgWidth * 0.042);
      ctx.setFillStyle('#DDC086');
      ctx.setTextAlign('left');
      ctx.fillText(title2, imgWidth * 0.63, imgHeight * 0.160);
      //绘制第2行文字
    }

    ctx.drawImage(wx.getStorageSync('qrcode'), imgWidth * 0.256, imgHeight * 0.465, imgWidth * 0.47, imgWidth * 0.42) //画二维码
    //绘制第一行文字
    ctx.setFontSize(imgWidth * 0.057);
    ctx.setFillStyle('#FFFFFF');
    ctx.setTextAlign('left');
    ctx.fillText(title1, imgWidth * 0.28, imgHeight * 0.160);
    //绘制第一行文字
   
    //绘制第3行文字
    ctx.setFontSize(imgWidth * 0.047);
    ctx.setFillStyle('#4A4D55');
    ctx.setTextAlign('left');
    ctx.fillText(title3, imgWidth * 0.15, imgHeight * 0.307);
    //绘制第3行文字
    //绘制第4行文字
    ctx.setFontSize(imgWidth * 0.037);
    ctx.setFillStyle('#4A4D55');
    ctx.setTextAlign('left');
    ctx.fillText(title4, imgWidth * 0.24, imgHeight * 0.345);
    //绘制第3行文字
    //绘制第3行文字
      /**
    ctx.drawImage(app.globalData.sharimg, 17, imgHeight * 0.435, imgWidth - 95, imgHeight * 0.53)**/ //第1张奖品
    //圆形切割-开始
    ctx.save();
   // ctx.beginPath();
    //ctx.arc(imgWidth * 0.30 / 2, imgHeight * 0.297, imgWidth * 0.15 / 2, 0, Math.PI * 2, false);

   // ctx.clip();
    //圆形切割-结束
   
    //ctx.drawImage(that.data.bgImgPath, imgWidth * 0.079, imgHeight * 0.253, imgHeight * 0.09, imgHeight * 0.09);//头像

    //圆形切割-开始
    ctx.stroke()
    ctx.draw()
    //绘制之后加一个延时去生成图片，如果直接生成可能没有绘制完成，导出图片会有问题。
    setTimeout(function () {
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: that.data.winwidth,
        height: that.data.winheight,
        destWidth: (that.data.winwidth) * 4,
        destHeight: (that.data.winheight) * 4,
        canvasId: 'shareCanvas',
        success: function (res) {
          that.setData({
            shareImage: res.tempFilePath,
            showSharePic: true
          })
          wx.hideLoading();
        },
        fail: function (res) {
          console.log(res)
          wx.hideLoading();
        }
      })
    }, 2000);
  },
  //适配不同屏幕大小的canvas    生成的分享图宽高分别是 750  和940，老实讲不知道这块到底需不需要，然而。。还是放了，因为不写这块的话，模拟器上的图片大小是不对的。。。
  setCanvasSize: function () {
    var size = {};
    try {
      var res = wx.getSystemInfoSync();
      var scale = 750;//画布宽度
      var scaleH = 940 / 750;//生成图片的宽高比例
      var width = res.windowWidth;//画布宽度
      var height = res.windowWidth * scaleH;//画布的高度
      size.w = width;
      size.h = height;
    } catch (e) {
      // Do something when catch error
      console.log("获取设备信息失败" + e);
    }
    return size;
  },
  savaImageToPhoto: function () {
    var self = this;

    wx.saveImageToPhotosAlbum({
      filePath: self.data.shareImage,
      success: function (res) {
        self.toast("保存成功");
      },
      fail: function (res) {
        self.toast("保存失败");
      }
    })
  },
  /*
  * 保存到相册
 */
  save: function () {
    var that = this;
    //获取相册授权
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {//这里是用户同意授权后的回调
              that.savaImageToPhoto();
            },
            fail() {//这里是用户拒绝授权后的回调
              that.toast("请授权相册");
              that.setData({
                openSettingBtnHidden: true
              })
            }
          })
        } else {//用户已经授权过了
          that.savaImageToPhoto();
        }
      }
    })
  },
  cancelAuth:function(){
    var that=this;
    that.setData({
      openSettingBtnHidden: false
    })
  },
  handleSetting: function (e) {
    var that = this;
    // 对用户的设置进行判断，如果没有授权，即使用户返回到保存页面，显示的也是“去授权”按钮；同意授权之后才显示保存按钮
    if (!e.detail.authSetting['scope.writePhotosAlbum']) {
      that.toast("若不打开授权，则无法将图片保存在相册中！");
    } else {
      that.toast("授权成功");
      that.setData({
        openSettingBtnHidden: false
      })
    }
  },
})